import random

"""
方法	                                描述	                         触发时机
__getattr__(self, name)	                访问不存在的属性时调用	          obj.nonexistent
__setattr__(self, name, value)	        所有属性赋值操作时调用	          obj.attr = value
__delattr__(self, name)	                删除属性时调用	                 del obj.attr
__dir__(self)	                        决定dir(obj)时返回的属性列表	  dir(obj)
"""
stu_obj = {"name": "jackie", "age": random.random()}

print(stu_obj.get("name"))


class DynamicAttributes:
    """动态属性管理类"""

    def __init__(self):
        self._data = {}
        self._access_count = {}

    def __getattr__(self, name):
        """访问不存在的属性时调用"""
        if name in self._data:
            self._access_count[name] = self._access_count.get(name, 0) + 1
            return self._data[name]
        else:
            raise AttributeError(
                f"'{type(self).__name__}' object has no attribute '{name}'"
            )

    def __setattr__(self, name, value):
        """赋值属性时调用"""
        if name.startswith("_"):
            super().__setattr__(name, value)
        else:
            if "_data" in self.__dict__:
                self._data[name] = value
                self._access_count[name] = 0
            else:
                super().__setattr__(name, value)

    def __delattr__(self, name):
        """删除属性时调用"""
        print("删除属性时调用")
        if name in self._data:
            del self._data[name]
            del self._access_count[name]
        else:
            super().__delattr__(name)

    def __dir__(self):
        """自定义 dir() 输出"""
        base_attrs = super().__dir__()
        dynamic_attrs = list(self._data.keys())
        return base_attrs + dynamic_attrs

    def get_access_stats(self):
        """返回访问次数统计表"""
        return self._access_count.copy()


# 使用示例
obj = DynamicAttributes()
obj.foo = 123
obj.bar = "hello"

print(obj.foo)  # 123
print(obj.bar)  # hello
print(obj.foo)  # 再次访问

del obj.bar

print("所有属性：", dir(obj))
print("访问次数统计：", obj.get_access_stats())
